package com.zhai.cloud.frame.msg.buffer.sender;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.support.CorrelationData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Map;
import java.util.UUID;

/**
 * @author Created by 翟凤玺
 * @package com.zhai.cloud.frame.msg.buffer.sender
 * @project-name zhai-cloud
 * @description 生产者-交易保存-业务
 * @create-datetime 2020-5-6 10:26
 */
@Slf4j
@Component
public class BizDealSaveSender implements RabbitTemplate.ReturnCallback, RabbitTemplate.ConfirmCallback {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Value("${biz.mq.deal-save.exchange.name}")
    private String exchange;

    @Value("${biz.mq.deal-save.routing-key.name}")
    private String routingKey;

    @PostConstruct
    public void init() {
        rabbitTemplate.setConfirmCallback(this);
        rabbitTemplate.setReturnCallback(this);
    }

    public void send(String serialNum, String message, Map<String, Object> header) {
        /** 创建消息 */
        Message msg = MessageBuilder.createMessage(message, new MessageHeaders(header));
        /** 设置消息流水号 */
        CorrelationData correlationData = new CorrelationData(serialNum);
        rabbitTemplate.convertAndSend(exchange, routingKey, msg, correlationData);
    }

    @Override
    public void confirm(CorrelationData correlationData, boolean ack, String cause) {
        log.info("confirm【消息发送到交换器Exchange后触发回调】: correlationData【消息唯一标识】:{},ack【确认结果】:{},cause【失败原因】:{}", correlationData, ack, cause);
    }

    @Override
    public void returnedMessage(org.springframework.amqp.core.Message message, int replyCode, String replyText, String exchange, String routingKey) {
        log.info("returnedMessage【消息从交换器发送到对应队列失败时触发】: message【消息主体】:{},replyCode:{},replyText【描述】:{},exchange【消息使用的交换器】:{},routingKey【消息使用的路由键】:{}", message, replyCode, replyText, exchange, routingKey);
    }
}